package org.darkforest.auth;

import org.darkforest.common.constant.Constants;
import org.darkforest.common.services.MemberService;
import org.darkforest.model.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import java.lang.annotation.Annotation;

/**
 * 获取当前用户CRUD
 *
 * @auth bingo
 * @create 2017-011-21-10:37
 */
@Component
public class CurrentMemberHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private MemberService memberService;


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果参数类型是Member并且有CurrentMember注解则支持
            Class<?> klass = methodParameter.getParameterType();
            if (klass.isAssignableFrom(Member.class)) {
                Annotation[] as = methodParameter.getParameterAnnotations();
                for (Annotation a : as) {
                    if (a.annotationType() == CurrentMember.class) {
                        return true;
                    }
                }
            }
            return false;

    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Long currentUserId =(Long) nativeWebRequest.getAttribute(Constants.CURRENT_MEMBER_ID, RequestAttributes.SCOPE_REQUEST);

        if(currentUserId!=null){
            return memberService.getMemberById(currentUserId.intValue());

        }
        throw new MissingServletRequestPartException(Constants.CURRENT_MEMBER_ID);
    }
}
